package yace;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * Created by yangluhua on 2016/12/5 0005.
 */
public class ForkJoinTest {

    private class ForkJoinTask extends RecursiveTask<Integer> {
        int[] d = createArrayOfRandomDoubles();
        private int first;
        private int last;
        public ForkJoinTask(int first, int last) {
            this.first = first;
            this.last = last;
        }
        protected Integer compute() {
            int subCount =0 ;
            if (last - first < 10) {
                subCount = 0;
                for (int i = first; i <= last; i++) {
                    if (d[i] < 0.5)
                        subCount++;
                }
            }
            else {
                int mid = (first + last) >>> 1;   //这种取中间值的方法很独特
                ForkJoinTask left = new ForkJoinTask(first, mid);
                left.fork();       //分割
                ForkJoinTask right = new ForkJoinTask(mid + 1, last);
                right.fork();      //分割
                subCount += left.join();     //合并
                subCount += right.join();   //合并
            }
            System.out.println("subCount:"+subCount);
            return subCount;
        }
    }

    public int[] createArrayOfRandomDoubles(){
        Random random = new Random();
        int[] d = new int[5];
        for (int i=0;i<5;i++){
            d[i] = random.nextInt(5);
            System.out.println(d[i]);
        }
         return d;
    }

    public static void main(String[] args) {
        ForkJoinTest forkJoinTest = new ForkJoinTest();
        int n = new ForkJoinPool().invoke(forkJoinTest.new ForkJoinTask(0, 4));
        System.out.println("Found " + n + " values");
    }
}
